<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <!-- <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialog">
            添加角色
          </el-button>
        </el-col>
      </el-row> -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="queryParams.roleKey"
            placeholder="请输入权限字符"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-row>
          <el-col> -->
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="mgr10"
          ></el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getRolesList"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
        <!-- <el-form-item> </el-form-item> -->
        <!-- </el-col>
        </el-row> -->
      </el-form>

      <el-row type="flex">
        <el-col>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="small"
            @click="addRoleDialog"
            >新增角色</el-button
          >
        </el-col>
        <el-col class="tr">
          <right-toolbar
            :show-search.sync="showSearch"
            @queryTable="getRolesList"
          ></right-toolbar>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table
        :data="rolesList"
        border
        stripe
        v-loading="loading"
        class="mgt10"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <template v-if="row.children.length">
              <el-row
                v-for="(level1, l1) in row.children"
                :key="level1.menuId"
                type="flex"
                align="middle"
                :class="['bdbottom', l1 === 0 ? 'bdtop' : '']"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="removeRightById(row, level1.menuId, level1)"
                  >
                    {{ level1.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <!-- 通过 for 循环 嵌套渲染二级权限 -->
                  <el-row
                    v-for="(level2, l2) in level1.children"
                    :key="level2.menuId"
                    type="flex"
                    align="middle"
                    :class="[l2 === 0 ? '' : 'bdtop']"
                  >
                    <!-- 二级权限列表渲染 -->
                    <el-col :span="6">
                      <el-tag
                        closable
                        type="success"
                        @close="removeRightById(row, level2.menuId, level2)"
                      >
                        {{ level2.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        v-for="level3 in level2.children"
                        :key="level3.menuId"
                        closable
                        type="warning"
                        @close="removeRightById(row, level3.menuId, level3)"
                      >
                        {{ level3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
            <template v-else>
              <div class="no-Rights">暂未分配权限</div>
            </template>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="创建时间">
          <template #default="{ row }">
            {{ row.createTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template #default="{ row }">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRole(row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRole(row.roleId)"
            >
              删除
            </el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="500px"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <!-- 默认展开所有节点属性 -->
      <!-- default-expand-all -->
      <el-checkbox
        v-model="menuExpand"
        @change="handleCheckedTreeExpand($event, 'treeRef')"
        >展开/折叠</el-checkbox
      >
      <el-checkbox
        v-model="menuNodeAll"
        @change="handleCheckedTreeNodeAll($event, 'treeRef')"
        >全选/全不选</el-checkbox
      >
      <el-tree
        class="tree-border"
        ref="treeRef"
        accordion
        :data="rightsList"
        :props="treetProps"
        empty-text="加载中，请稍后"
        show-checkbox
        node-key="menuId"
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="allotRights">确 定</el-button>
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="500px"
      @close="addRoleDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        :rules="addRoleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="权限字符：" prop="roleKey">
          <el-input v-model="addRoleForm.roleKey"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限：">
          <el-checkbox
            v-model="addRoleForm.menuExpand"
            @change="handleCheckedTreeExpand($event, 'addtreeRef')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="addRoleForm.menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'addtreeRef')"
            >全选/全不选</el-checkbox
          >
          <!-- @check-change="handleCheckChange('addtreeRef')" -->
          <el-tree
            class="tree-border"
            ref="addtreeRef"
            accordion
            :data="rightsList"
            :props="treetProps"
            show-checkbox
            node-key="menuId"
            :default-expand-all="addRoleForm.menuExpand"
          ></el-tree>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="500px"
      @close="editRoleDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        :rules="editRoleRules"
        label-width="120px"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="权限字符：" prop="roleKey">
          <el-input v-model="editRoleForm.roleKey"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleConf">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  addRoles,
  updateRoles,
  delRoles,
  getTree,
  setRoleRights,
  cancelRoleRights
} from '@/api/role'
import RightToolbar from '@/components/RightToolbar'

export default {
  components: {
    RightToolbar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        roleName: undefined,
        roleKey: undefined,
        dateRange: []
      },
      menuExpand: false,
      menuNodeAll: false,
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限弹框显示隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treetProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配的权限的角色id
      roleId: '',
      // 控制添加角色弹框的显示与隐藏
      addRoleDialogVisible: false,
      // 控制编辑角色弹框的显示与隐藏
      editRoleDialogVisible: false,
      // 添加角色表单数据
      addRoleForm: {
        menuExpand: false,
        menuNodeAll: false,
        // 角色名称
        roleName: '',
        // 角色描述
        roleDesc: '',
        roleKey: '' // 权限字符
      },
      // 添加角色表单校验
      addRoleRules: {
        // 角色名称表单校验
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        // 角色描述表单校验
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '请输入权限字符', trigger: 'blur' }
        ]
      },
      // 编辑角色表单数据
      editRoleForm: {
        // 角色名称
        roleName: '',
        // 角色描述
        roleDesc: '',
        roleKey: '' // 权限字符
      },
      // 编辑角色表单校验
      editRoleRules: {
        // 角色名称表单校验
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        // 角色描述表单校验
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '请输入权限字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1
      // this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.getRolesList()
    },
    // handleCheckChange(refName) {
    //   const len = [
    //     ...this.$refs[refName].getCheckedKeys(),
    //     ...this.$refs[refName].getHalfCheckedKeys()
    //   ].length
    //   //  this.getLeafKeys(row, this.defKeys)
    //   const arr = []
    //   this.rightsList.forEach(item => {
    //     this.getLeafKeys(item, arr)
    //   })
    // },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, refName) {
      const treeList = this.rightsList
      for (let i = 0; i < treeList.length; i++) {
        this.$refs[refName].store.nodesMap[treeList[i].menuId].expanded = value
        for (let j = 0; j < treeList[i].children.length; j++) {
          this.$refs[refName].store.nodesMap[
            treeList[i].children[j].menuId
          ].expanded = value
        }
      }
    },
    async handleCheckedTreeNodeAll(value, refName) {
      this.$refs[refName].setCheckedNodes(value ? this.rightsList : [])
    },
    // 新增角色
    async addRoleDialog() {
      // 获取所有权限数据
      const { _RejCode, data } = await getTree()
      if (_RejCode !== '00000000') return
      this.rightsList = data
      this.addRoleDialogVisible = true
    },
    // 获取所有角色列表
    async getRolesList() {
      this.loading = true
      const { _RejCode, data } = await getRoles(this.queryParams).catch(
        (err) => err
      )
      this.loading = false
      if (_RejCode !== '00000000') return
      this.rolesList = data
    },
    // 根据id删除对应的权限
    async removeRightById(row, rightId, level) {
      console.log(row, level, rightId)
      const arr = []
      this.getLeafKeys(level, arr)
      row.children.forEach((item) => {
        if (item.children && item.children.length === 1) {
          item.children.forEach((ele) => {
            if (ele.menuId === rightId) {
              arr.push(item.menuId)
            }
          })
        }
      })
      // 弹框提示 删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消权限删除')
      }
      const { _RejCode, _RejMsg, data } = await cancelRoleRights({
        roleId: row.roleId,
        rightId: [...new Set([...arr, rightId])]
      })
      if (_RejCode !== '00000000') return
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(row.children)
      this.$message.success(_RejMsg)
      this.$set(row, 'children', data)
      // row.children =
      // row = data
      // console.log(row, level)
      // row.children =
    },
    // 显示分配权限弹框
    async showSetRightDialog(row) {
      this.roleId = row.roleId
      // 获取所有权限数据
      const { _RejCode, data } = await getTree()
      if (_RejCode !== '00000000') return
      this.rightsList = data
      this.getLeafKeys(row, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归形式，获取角色下所有三级权限的id，并保存到 defkeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.menuId)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.menuNodeAll = false
      this.menuExpand = false
      this.defKeys = []
    },
    // 点击确定为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // const idStr = keys.join(',')
      const { _RejCode, _RejMsg } = await setRoleRights({
        roleId: this.roleId,
        rights: keys.sort((x, y) => x - y)
      })
      if (_RejCode !== '00000000') return
      this.getRolesList()
      this.$message.success(_RejMsg)
      this.setRightDialogVisible = false
    },
    // 监听添加角色对话框的关闭事件
    addRoleDialogClosed() {
      this.addRoleForm.menuExpand = false
      this.addRoleForm.menuNodeAll = false
      this.$refs.addRoleFormRef.resetFields()
    },
    // 点击确定按钮添加角色
    async addRoles() {
      const rights = [
        ...this.$refs.addtreeRef.getCheckedKeys(),
        ...this.$refs.addtreeRef.getHalfCheckedKeys()
      ].sort((x, y) => x - y)
      const { _RejCode, _RejMsg } = await addRoles({
        ...this.addRoleForm,
        rights
      })
      if (_RejCode !== '00000000') return
      this.$message.success(_RejMsg)
      this.getRolesList()
      this.addRoleDialogVisible = false
    },
    // 编辑角色
    async editRole(row) {
      const { _RejCode, data } = await getRoles({ roleId: row.roleId })
      if (_RejCode !== '00000000') return
      console.log(data)
      this.editRoleForm = data[0]
      this.editRoleDialogVisible = true
    },
    // 点击编辑角色对话框确定按钮修改角色信息
    async editRoleConf() {
      const { _RejCode, _RejMsg } = await updateRoles({
        // ...this.editRoleForm
        roleId: this.editRoleForm.roleId,
        roleName: this.editRoleForm.roleName,
        roleDesc: this.editRoleForm.roleDesc,
        roleKey: this.editRoleForm.roleKey
      })
      if (_RejCode !== '00000000') return
      this.$message.success(_RejMsg)
      this.getRolesList()
      this.editRoleDialogVisible = false
    },
    // 监听编辑角色对话框的关闭事件
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 删除角色
    async delRole(roleId) {
      // 弹框提示用户是否确认删除
      const confirmRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      if (confirmRes !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { _RejCode, _RejMsg } = await delRoles({ roleId })
      if (_RejCode !== '00000000') return
      // 如果用户取消了删除，则返回值为字符串 cancel
      this.$message.success(_RejMsg)
      this.getRolesList()
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.no-Rights {
  text-align: center;
}
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #fff none;
  border-radius: 4px;
}
</style>
